/**
 * 
 */
package com.hz.winnie.demands.web.controller.demand;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hz.winnie.demands.common.DemandsConstants;
import com.hz.winnie.demands.pojo.DemLifeCycle;
import com.hz.winnie.demands.pojo.Demand;
import com.hz.winnie.demands.pojo.Product;
import com.hz.winnie.demands.pojo.Role;
import com.hz.winnie.demands.pojo.User;
import com.hz.winnie.demands.service.DemLifeCycleService;
import com.hz.winnie.demands.service.DemandsService;
import com.hz.winnie.demands.service.ProductService;
import com.hz.winnie.demands.service.UserService;

/**
 * @description 需求controller
 * @author winnie
 * @date 2011-4-17
 * @version 1.0
 */
@Controller
@RequestMapping("/demand")
public class DemandController {

    private static int limit = 10;

    @Autowired
    private DemandsService demandsService;

    @Autowired
    private ProductService productService;

    @Autowired
    private UserService userService;

    @Autowired
    private DemLifeCycleService demLifeCycleService;

    @Autowired
    private HttpSession session;

    @InitBinder
    protected void initBinder(HttpServletRequest request,
	    ServletRequestDataBinder binder) throws Exception {
	binder.registerCustomEditor(Date.class, new CustomDateEditor(
		new SimpleDateFormat("yyyy-MM-dd"), true));

	binder.registerCustomEditor(Integer.class, null,
		new CustomNumberEditor(Integer.class, null, true));
    }

    /**
     * 新建需求
     * 
     * @param demand
     * @param model
     * @return
     */
    @RequestMapping("/add")
    public String add(@ModelAttribute Demand demand,
	    @RequestParam String productId, Model model) {
	if (demand == null || StringUtils.isBlank(demand.getTitle())) {
	    if (StringUtils.isBlank(productId)) {
		return "error";
	    }
	    List<User> pds = userService.getUsersByRole(Role.PD);
	    Product product = productService.getProductById(productId);
	    model.addAttribute("product", product);
	    model.addAttribute("pds", pds);
	    return "demand/add";
	}
	if (demandsService.isSameName(demand.getTitle(), null)) {
	    model.addAttribute("msg", "需求标题重复");
	    return "error";
	}
	int demandId = demandsService.addDemand(demand);
	model.addAttribute("demandId", demandId);
	return "demand/success";
    }

    /**
     * 修改需求
     * 
     * @param demand
     * @param model
     * @param demandId
     * @return
     */
    @RequestMapping("/edit/{demandId}")
    public String edit(@ModelAttribute Demand demand, Model model,
	    @PathVariable String demandId) {
	if (demand == null || StringUtils.isBlank(demand.getTitle())) {
	    if (StringUtils.isBlank(demandId)) {
		return "error";
	    }
	    List<User> pds = userService.getUsersByRole(Role.PD);
	    demand = demandsService.getDemandById(demandId);
	    Product product = productService.getProductById(String
		    .valueOf(demand.getProductId()));
	    demand = demandsService.getDemandById(demandId);
	    model.addAttribute("product", product);
	    model.addAttribute("demand", demand);
	    model.addAttribute("pds", pds);
	    return "demand/edit";
	}
	if (demandsService.isSameName(demand.getTitle(), demandId)) {
	    model.addAttribute("msg", "需求标题重复");
	    return "error";
	}
	demand.setId(Integer.valueOf(demandId));
	demandsService.updateDemand(demand);
	model.addAttribute("demandId", demandId);
	model.addAttribute("isEdit", true);
	return "demand/success";
    }

    /**
     * 需求详情
     * 
     * @param demandId
     * @param model
     * @return
     */
    @RequestMapping("/detail/{demandId}")
    public String detail(@PathVariable String demandId, Model model) {
	if (StringUtils.isBlank(demandId)) {
	    return "error";
	}
	Demand demand = demandsService.getDemandById(demandId);
	Product product = productService.getProductById(String.valueOf(demand
		.getProductId()));
	List<DemLifeCycle> lifeCycles = demLifeCycleService
		.listLifeCycleByDemandId(Integer.valueOf(demandId));

	model.addAttribute("demand", demand);
	model.addAttribute("product", product);
	model.addAttribute("lifeCycles", lifeCycles);
	return "demand/detail";
    }

    /**
     * 删除需求
     * 
     * @param demandId
     * @return
     */
    @RequestMapping("/delete/{demandId}")
    @ResponseBody
    public String delete(@PathVariable String demandId) {
	if (StringUtils.isBlank(demandId)) {
	    return Boolean.FALSE.toString();
	}
	demandsService.delete(demandId);
	return Boolean.TRUE.toString();
    }

    /**
     * 搜索需求
     * 
     * @param demand
     * @param model
     * @return
     */
    @RequestMapping("/search")
    public String search(@ModelAttribute Demand demand, Model model,
	    @RequestParam(defaultValue = "1") String currentPage) {
	if (demand == null) {
	    model.addAttribute("resultCount", 0);
	    return "demand/search";
	}
	if (demand.getProductId() != 0) {
	    Product product = productService.getProductById(String
		    .valueOf(demand.getProductId()));
	    model.addAttribute("product", product);
	}
	demand.setCurrentPage(Integer.valueOf(currentPage));
	assembleSearchParam(demand, model);
	return "demand/search";
    }

    /**
     * 未完成的需求
     * 
     * @param productId
     * @param model
     * @return
     */
    @RequestMapping("/undo/product/{productId}")
    public String undoDemandsForProduct(@PathVariable String productId,
	    Model model, @RequestParam(defaultValue = "1") String currentPage) {
	Demand demand = new Demand();
	demand.setProductId(Integer.valueOf(productId));
	String[] statuslist = { DemandsConstants.DEM_STATUS_UN_FOLLOW,
		DemandsConstants.DEM_STATUS_FOLLOWING };
	demand.setStatuslist(statuslist);
	demand.setCurrentPage(Integer.valueOf(currentPage));
	assembleSearchParam(demand, model);
	return "demand/search";
    }

    /**
     * 我的需求
     * 
     * @param model
     * @return
     */
    @RequestMapping( { "/my/{userId}", "/my" })
    public String myDemands(@PathVariable String userId, Model model,
	    @RequestParam(defaultValue = "1") String currentPage,
	    @ModelAttribute Demand demand) {
	if (demand == null) {
	    demand = new Demand();
	}
	if (StringUtils.isBlank(userId)) {
	    User demUser = (User) session
		    .getAttribute(DemandsConstants.SESSION_KEY_USER);
	    userId = String.valueOf(demUser.getId());
	}
	demand.setUserId(Integer.valueOf(userId));
	User user = userService.getUserById(userId);

	// 我的未完成个数
	String[] statuslist = { DemandsConstants.DEM_STATUS_UN_FOLLOW,
		DemandsConstants.DEM_STATUS_FOLLOWING };
	demand.setStatuslist(statuslist);
	int myUnDoDemCount = demandsService.countDemandsByCondition(demand);

	demand.setStatuslist(null);
	assembleSearchParam(demand, model);
	model.addAttribute("user", user);
	model.addAttribute("myUnDoDemCount", myUnDoDemCount);
	return "demand/myDemands";
    }

    /**
     * 我未完成的需求
     * 
     * @param model
     * @return
     */
    @RequestMapping("/undo/my")
    public String myUndoDemands(Model model,
	    @RequestParam(defaultValue = "1") String currentPage) {
	Demand demand = new Demand();
	User demUser = (User) session
		.getAttribute(DemandsConstants.SESSION_KEY_USER);
	int userId = demUser.getId();
	demand.setUserId(userId);
	String[] statuslist = { DemandsConstants.DEM_STATUS_UN_FOLLOW,
		DemandsConstants.DEM_STATUS_FOLLOWING };
	demand.setStatuslist(statuslist);
	assembleSearchParam(demand, model);
	return "demand/search";
    }

    /**
     * 新转交给我的需求
     * 
     * @param model
     * @return
     */
    @RequestMapping("/new/my")
    public String toMeNewDemands(Model model,
	    @RequestParam(defaultValue = "1") String currentPage) {
	Demand demand = new Demand();
	User demUser = (User) session
		.getAttribute(DemandsConstants.SESSION_KEY_USER);
	int userId = demUser.getId();
	demand.setUserId(userId);
	demand.setIsNew(DemandsConstants.DEM_IS_NEW_YES);
	assembleSearchParam(demand, model);
	return "demand/search";
    }

    /**
     * 我的已过期需求
     * 
     * @param model
     * @return
     */
    @RequestMapping("/overdue/my")
    public String overdueDemands(Model model,
	    @RequestParam(defaultValue = "1") String currentPage) {
	Demand demand = new Demand();
	User demUser = (User) session
		.getAttribute(DemandsConstants.SESSION_KEY_USER);
	int userId = demUser.getId();
	demand.setUserId(userId);
	String[] statuslist = { DemandsConstants.DEM_STATUS_UN_FOLLOW,
		DemandsConstants.DEM_STATUS_FOLLOWING };
	demand.setStatuslist(statuslist);
	demand.setEndTime(new Date());
	assembleSearchParam(demand, model);
	return "demand/search";
    }

    /**
     * 我的快到期需求
     * 
     * @param model
     * @return
     */
    @RequestMapping("/crash/my")
    public String crashDemands(Model model,
	    @RequestParam(defaultValue = "1") String currentPage) {
	Demand demand = new Demand();
	User demUser = (User) session
		.getAttribute(DemandsConstants.SESSION_KEY_USER);
	int userId = demUser.getId();
	demand.setUserId(userId);
	String[] statuslist = { DemandsConstants.DEM_STATUS_UN_FOLLOW,
		DemandsConstants.DEM_STATUS_FOLLOWING };
	demand.setStatuslist(statuslist);
	demand.setStartTime(new Date());
	demand.setEndTime(DateUtils.addDays(new Date(), -7));
	assembleSearchParam(demand, model);
	return "demand/search";
    }

    /**
     * 搜索前组装条件
     * 
     * @param demand
     * @param model
     */
    private void assembleSearchParam(Demand demand, Model model) {
	demand.setLimit(limit);
	if (demand.getCurrentPage() == 0) {
	    demand.setCurrentPage(1);
	}
	int start = (demand.getCurrentPage() - 1) * limit;
	demand.setStart(start);
	List<Demand> demands = demandsService.listDemandsByCondition(demand);
	int count = demandsService.countDemandsByCondition(demand);
	model.addAttribute("demands", demands);
	model.addAttribute("demand", demand);
	model.addAttribute("resultCount", count);
	model.addAttribute("totalPages", count % limit == 0 ? count / limit
		: count / limit + 1);
	model.addAttribute("currentPage", demand.getCurrentPage());
    }

    /**
     * 是否有相同名字的需求，如果传递demandId表示是修改的时候，要出去这个需求本身
     * 
     * @param name
     * @param productId
     * @return
     */
    @RequestMapping("/isSameName/{title}/{demandId}")
    @ResponseBody
    public String isSameName(@PathVariable String title,
	    @PathVariable String demandId) {
	if (demandsService.isSameName(title, demandId)) {
	    return Boolean.TRUE.toString();
	}
	return Boolean.FALSE.toString();
    }

    /**
     * 已读
     * 
     * @param demandId
     * @return
     */
    @RequestMapping("/readed/{userId}/{demandId}")
    @ResponseBody
    public String readed(@PathVariable String demandId,
	    @PathVariable String userId) {
	demandsService.markReaded(demandId, userId);
	return Boolean.TRUE.toString();
    }
}
